package team.zero.lemon.module.sys.service;

import team.zero.lemon.common.exception.CustomException;
import team.zero.lemon.common.persistence.Page;
import team.zero.lemon.common.service.CrudService;
import team.zero.lemon.module.sys.dao.IRoleDao;
import team.zero.lemon.module.sys.dao.IRoleFunctionDao;
import team.zero.lemon.module.sys.entity.Role;
import team.zero.lemon.module.sys.entity.RoleFunction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by bolin on 2016/5/10.
 */
@Service
public class RoleService extends CrudService<IRoleDao, Role> {

    @Autowired
    private IRoleFunctionDao roleFunctionDao;

    public List<Role> findRoleByUserId(int id) {
        try {
            return dao.findByUserId(id);
        } catch (Exception e) {
            throw new CustomException(e);
        }
    }
    public List<Role> findByParameter(Role role) {
        try {
            return dao.findByParameter(role);
        } catch (Exception e) {
            throw new CustomException(e);
        }
    }
    public List<Role> findRoleTree( ) {
        try {
            return dao.findRoleTree();
        } catch (Exception e) {
            throw new CustomException(e);
        }
    }
    public List<RoleFunction> findFunctionByRoleId(RoleFunction roleFunction) {
        try {
            return roleFunctionDao.findByRoleId(roleFunction.getRoleId());
        } catch (Exception e) {
            throw new CustomException(e);
        }
    }

    @Transactional
    public int saveRoleFunction(List<RoleFunction> roleFunctionList) {
        try {
            roleFunctionDao.deleteByroleId(roleFunctionList.get(0).getRoleId());
            for (RoleFunction roleFunction : roleFunctionList) {
                roleFunction.preInsert();
            }
            return roleFunctionDao.insert(roleFunctionList);

        } catch (Exception e) {
            throw new CustomException(e);
        }
    }

    @Transactional
    public int roleFunctionDelete(List<RoleFunction> roleFunctionList) {
        try {
            return roleFunctionDao.deleteByroleId(roleFunctionList.get(0).getRoleId());
        } catch (Exception e) {
            throw new CustomException(e);
        }
    }
}
